package com.rt.java.util.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        RRWLCache.put("name", "张三");
        RRWLCache.get("name"); // 张三
    }
}

class RRWLCache {
    private static ReentrantReadWriteLock rrwl = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = rrwl.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = rrwl.writeLock();
    private static Map<String, Object> cache = new HashMap<>();

    public static Object get(String key) {
        readLock.lock();
        new Thread(() -> {
            readLock.lock();
        }).start();
        try {
            return cache.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public static void put(String key, Object value) {
        writeLock.lock();
        /*new Thread(() -> {
            writeLock.lock();
        }).start();*/
        try {
            cache.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

}